package org.androidpn.server.xmpp.handler;

import java.util.Date;

import org.androidpn.server.entity.Friend;
import org.androidpn.server.entity.FriendGroup;
import org.androidpn.server.entity.FriendMessage;
import org.androidpn.server.entity.FriendMessage.FriendMessageStatus;
import org.androidpn.server.entity.Role;
import org.androidpn.server.service.FriendGroupService;
import org.androidpn.server.service.FriendMessageService;
import org.androidpn.server.service.FriendService;
import org.androidpn.server.service.RoleService;
import org.androidpn.server.service.ServiceLocator;
import org.androidpn.server.xmpp.UnauthorizedException;
import org.androidpn.server.xmpp.packet.FriendMessagePacket.Operation;
import org.androidpn.server.xmpp.push.PushFriendMessageToClientThread;
import org.androidpn.server.xmpp.session.ClientSession;
import org.dom4j.Element;
import org.jivesoftware.smack.util.StringUtils;
import org.xmpp.packet.IQ;
import org.xmpp.packet.PacketError;

/**
 * This class is to handle the TYPE_IQ jabber:iq:roster protocol.
 * 
 * @author Sehwan Noh (devnoh@gmail.com)
 */
public class IQFriendMessageHandler extends IQHandler {

	private static final String NAMESPACE = "jabber:iq:friendMessage";

	private FriendService friendService = null;

	private FriendGroupService friendGroupService = null;

	private RoleService roleService = null;

	private FriendMessageService friendMessageService = null;

	/**
	 * Constructor.
	 */
	public IQFriendMessageHandler() {
		friendService = (FriendService) ServiceLocator
				.getService(ServiceLocator.FRIEND_SERVICE);
		friendGroupService = (FriendGroupService) ServiceLocator
				.getService(ServiceLocator.FRIEND_GROUP_SERVICE);
		roleService = (RoleService) ServiceLocator
				.getService(ServiceLocator.ROLE_SERVICE);
		friendMessageService = (FriendMessageService) ServiceLocator
				.getService(ServiceLocator.FRIEND_MESSAGE_SERVICE);
	}

	/**
	 * Handles the received IQ packet.
	 * 
	 * @param packet
	 *            the packet
	 * @return the response to send back
	 * @throws UnauthorizedException
	 *             if the user is not authorized
	 */
	public IQ handleIQ(IQ packet) throws UnauthorizedException {
		IQ reply = null;

		ClientSession session = sessionManager.getSession(packet.getFrom());

		try {
			Element query = packet.getChildElement();
			reply = IQ.createResultIQ(packet);
			String operationStr = query.elementText("operation");
			if (operationStr != null && !operationStr.equals("")) {
				Operation operation = Operation.valueOf(operationStr);
				switch (operation) {
				case getMessage:
					Long roleId = Long.valueOf(query.elementText("roleId"));
					new Thread(new PushFriendMessageToClientThread(roleId,
							sessionManager)).start();
					break;
				case pushMessage:
					break;
				case sendMessage:
					sendMessage(reply, query);
					break;
				default:
					reply.setError(PacketError.Condition.feature_not_implemented);
					break;
				}
			} else {
				reply = null;
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			reply.setError(PacketError.Condition.feature_not_implemented);
		}
		if (reply != null) {
			session.process(reply);
		}
		return null;
	}

	private void sendMessage(IQ reply, Element query) {
		FriendMessage friendMessage = FriendMessage.fromXML(StringUtils
				.unescapeNode(query.elementText("friendMessage")));
		System.out.println(StringUtils.unescapeNode(query.asXML()));
		friendMessage.setId(null);
		friendMessage.setCreateDate(new Date());
		friendMessage.setModifyDate(new Date());
		friendMessage.setFriendMessageStatus(FriendMessageStatus.sending);
		Role receiver = friendMessage.getReceiver();
		receiver = roleService.find(receiver.getId());
		Role sender = friendMessage.getSender();

		Friend toFriend = friendService.findFriend(sender.getId(),
				receiver.getId());
		// 判断是否在对方黑名单中
		if (toFriend == null) {
			reply.setError(PacketError.Condition.forbidden);
			return;
		}
		FriendGroup toFriendGroup = toFriend.getFriendGroup();
		if (toFriendGroup != null && toFriendGroup.getIsBlacklist()) {
			reply.setError(PacketError.Condition.forbidden);
			return;
		}
		friendMessageService.save(friendMessage);
		new Thread(new PushFriendMessageToClientThread(receiver.getId(),
				sessionManager)).start();
	}

	public String getNamespace() {
		return NAMESPACE;
	}
}
